/*******************************************************************************
 * Copyright 2007, 2009 InnovaSoft SA http://www.innovasoft.biz/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
 
package biz.innovasoft.nodb.index;

import java.io.IOException;

import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumberTools;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.SingleInstanceLockFactory;

import biz.innovasoft.nodb.util.IndexUtils;

public class Indexer  {

	private transient IndexManager index;
	private transient IndexWriter writer;
	private transient boolean optimize = false;

	public Indexer () {
	}
	
	public Indexer(IndexManager index) throws IndexException {
		this(index, false, false);
	}

	public Indexer(IndexManager index, boolean reindex) throws IndexException {
		this(index, reindex, false);
	}

	public Indexer(IndexManager index, boolean reindex, boolean optimize)
			throws IndexException {
		this.optimize = optimize;
		if (index.getDirectory().getLockFactory() == null) {
			index.getDirectory()
					.setLockFactory(new SingleInstanceLockFactory());
		}
		
		this.index = index;
		
		try {
			if (reindex) {
				writer = new IndexWriter(this.index.getDirectory(),
						new SimpleAnalyzer(), true,
						IndexWriter.MaxFieldLength.UNLIMITED);
			} else {
				writer = new IndexWriter(this.index.getDirectory(),
						new SimpleAnalyzer(),
						IndexWriter.MaxFieldLength.UNLIMITED);
			}
		} catch (Exception e) {
			throw new IndexException("Error opening index.", e);
		}
	}
	
	public void indexObject (Long oid, Object object) throws IndexException {
		try {
			/* The Object Id */
			Field fieldOid = new Field("oid", NumberTools.longToString(oid), Field.Store.YES,
					Field.Index.NOT_ANALYZED);
			
			Document pdoc = null;
			pdoc = IndexUtils.buildDocument(this.index, object);
			pdoc.add (fieldOid);
			writer.addDocument(pdoc);
			
		} catch (IOException e) {
			throw new IndexException(
					"Error indexing object with oid: " + index, e);
		}
		
	}
	
	public void close() {
		try {
			if (optimize) {
				writer.optimize();
			}
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
